﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Abp.Runtime.Session;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sunlit.House.Authorization.Users;
using Sunlit.House.Configuration;
using Sunlit.House.Wechat.Dto;
using Sunlit.House.Helper;
using Sunlit.House.Timing;
using Abp.Application.Services;

namespace Sunlit.House.Wechat
{
    public class WechatAppService: HouseAppServiceBase, IWechatAppService
    {
        public const string ProviderName = "WechatMiniProgram";
        const string url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&grant_type=authorization_code&js_code={2}";
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly UserManager _userManager;
        private readonly IConfigurationRoot _appConfiguration;
        public string AppId => _appConfiguration["Authentication:WechatMiniProgram:AppId"];
        public string AppSecret => _appConfiguration["Authentication:WechatMiniProgram:AppSecret"];
        public WechatAppService(
            IHttpClientFactory httpClientFactory,
            UserManager userManager,
            IAppConfigurationAccessor configurationAccessor)
        {
            _httpClientFactory = httpClientFactory;
            _userManager = userManager;
            _appConfiguration = configurationAccessor.Configuration;
        }
        [HttpPost]
        public async Task<GetOpenIdOutput> GetOpenId(GetOpenIdInput input)
        {
            string geturl = string.Format(url, AppId, AppSecret, input.JsCode);
            HttpClient client = _httpClientFactory.CreateClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var result = await client.GetAsync(geturl);
            if (result.IsSuccessStatusCode)
            {
                string re = await result.Content.ReadAsStringAsync();
                var m = JsonConvert.DeserializeObject<GetOpenIdOutput>(re);

                return m;
            }
            return null;
        }
        [RemoteService(false)]
        public string DecryptData(string encryptData,string sessionKey, string iv)
        {
            WXBizDataCrypt wXBizDataCrypt = new WXBizDataCrypt(AppId, sessionKey);
            var deData = wXBizDataCrypt.DecryptData(encryptData, iv);
            return deData;
        }
    }
}
